﻿using AutoMapper;
using B.S.BasicData.Api.Write.Applications.Command;
using B.S.BasicData.Domains;
using B.S.BasicData.ErrorCode;
using B.S.BasicData.Infrastructures;
using MediatR;

namespace B.S.BasicData.Api.Write.Applications.CommandHandler
{
    public class UpdateUserRoleCommandHandler : IRequestHandler<UpdateUserRoleCommand, ApiResult<int>>
    {
        private readonly IBaseRepository<UserInfos> userRepository;
        private readonly IBaseRepository<RoleUser> roleuserRepository;
        private readonly IMapper mapper;
        private readonly ILogger<AddRoleUserCommandHandler> logger;

        public UpdateUserRoleCommandHandler(IBaseRepository<UserInfos> userRepository, IBaseRepository<RoleUser> roleuserRepository, IMapper mapper, ILogger<AddRoleUserCommandHandler> logger)
        {
            this.userRepository = userRepository;
            this.roleuserRepository = roleuserRepository;
            this.mapper = mapper;
            this.logger = logger;
        }
        public async Task<ApiResult<int>> Handle(UpdateUserRoleCommand request, CancellationToken cancellationToken)
        {
            ApiResult<int> result = new ApiResult<int>();
            result.Code = ApiEnum.Success;
            result.Message = "角色用户添加成功";
            using (var tran = userRepository.DB.Database.BeginTransaction())
            {
                try
                {
                    logger.LogInformation("修改用户角色成功");
                    //角色
                    UserInfos UserInfos = mapper.Map<UserInfos>(request);
                    
                   await userRepository.Update(UserInfos);
                    //角色权限
                    var listSelect = roleuserRepository.GetAll().Where(x => x.UserId == request.UserId).ToList();
                    await roleuserRepository.Delete(listSelect);
                    var list = new List<RoleUser>();
                    foreach (var item in request.RoleIds)
                    {
                        list.Add(new RoleUser()
                        {
                            UserId = request.UserId,
                            RoleId = item
                        });
                    }
                    await roleuserRepository.AddRange(list);
                    tran.Commit();
                }
                catch (Exception ex)
                {
                    logger.LogInformation("修改角色权限失败" + ex.Message);
                    result.Code = ApiEnum.Fail;
                    result.Message = "修改角色权限失败";
                    tran.Rollback();
                }
            }
            return await Task.FromResult(result);
        }
    }
    }

